package com.cwt_taxi_xa.protocol.config;

import com.cwt_taxi_xa.protocol.MeterEncoder;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.Tools;

/**
 * Created by undi on 2019/9/16 16:27
 * 计价器运营时间
 */
public class MeterConfigTask {
    private String TAG = "MeterConfigTask";
    private boolean needUpdate = false;
    private byte[] cacheBuffer;
    public boolean isNeedUpdate() {
        return needUpdate;
    }

    public void setNeedUpdate(boolean needUpdate) {
        //this.needUpdate = needUpdate;
    }

    public void cacheParam(byte[] buffer){
        if(buffer != null && isNeedUpdate()){
            //缓存计价器参数
            cacheBuffer = new byte[buffer.length];
            System.arraycopy(buffer,0,cacheBuffer,0,buffer.length);
            startUpdate();
        }else{
            setNeedUpdate(false);
        }
    }
    public void settingParamInfo(byte[] buffer){
        if(buffer != null){
            AppLog.e(TAG,"settingParamInfo buffer:" + Tools.parseByte2HexStr(buffer));
        }else{
            AppLog.e(TAG,"settingParamInfo buffer:null!");
        }
    }
    /**
     * 执行更新
     */
    private void startUpdate(){
        if(cacheBuffer != null){
            setNeedUpdate(false);
            try {
                byte[] nowSettingData = Tools.str2Bcd(DateUtil.getNowDateToMeterSetting());
                AppLog.d(TAG,"nowSettingData:" + Tools.parseByte2HexStr(nowSettingData));
                AppLog.d(TAG,"cacheBuffer 1:" + Tools.parseByte2HexStr(cacheBuffer));
                //更新日期
                System.arraycopy(nowSettingData,0,cacheBuffer,0,nowSettingData.length);
                AppLog.d(TAG,"cacheBuffer 2:" + Tools.parseByte2HexStr(cacheBuffer));

                byte[] configData = MeterEncoder.getMeterDtuBody("0005",cacheBuffer);
                AppLog.d(TAG,"configData 2:" + Tools.parseByte2HexStr(configData));
                sendSerialData6(configData);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 查询计价器参数设置
     */
    public void queryRateParam(){
        if(isNeedUpdate()){
            sendSerialData6(MeterEncoder.queryRateParam());
        }
    }

    private void sendSerialData6(byte[] buffer){
        SerialPortService.getInstance().sendSerialData6(buffer);
    }
}
